package co.infinum.goldfinger.rx;

import co.infinum.goldfinger.Goldfinger;
import co.infinum.goldfinger.RestartPredicates;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

class RxGoldfingerImpl implements RxGoldfinger {
    @NonNull
    private final Goldfinger goldfinger;
    @Nullable
    private RxGoldfingerCallback callback;
    private boolean listening;

    RxGoldfingerImpl(@NonNull Goldfinger goldfinger) {
        this.goldfinger = goldfinger;
    }

    @NonNull
    @Override
    public Observable<Goldfinger.Result> authenticate() {
        return Observable.create(new ObservableOnSubscribe<Goldfinger.Result>() {
            @Override
            public void subscribe(ObservableEmitter<Goldfinger.Result> emitter) {
                callback = new RxGoldfingerCallback(emitter);
                goldfinger.authenticate(RestartPredicates.defaultPredicate(), callback);
            }
        });
    }

    @Override
    public int isHardwarePresent() {
        return goldfinger.isHardwarePresent();
    }

    @Override
    public void cancel() {
        if (callback != null) {
            callback.cancel();
        }
        goldfinger.cancelAuthentication();
    }

    @Override
    public Observable<Goldfinger.Result> encrypt(Goldfinger.RestartPredicate restartPredicate, String key, String value) {
        return Observable.create(new ObservableOnSubscribe<Goldfinger.Result>() {
            @Override
            public void subscribe(ObservableEmitter<Goldfinger.Result> emitter) {
                callback = new RxGoldfingerCallback(emitter);
                goldfinger.encrypt(restartPredicate, key, value, callback);
            }
        });
    }
}
